package de.uni_mannheim.informatik.ai.dame_ai.util;


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


@SuppressWarnings("serial")
public class SaveGameDialog extends FileAccessDialog{

	private JButton butCancel= new MinSizeButton("Abbrechen");
	private JButton butSave= new MinSizeButton("Speichern");
	private JLabel instruction= new JLabel("Bitte geben sie einen namen für den spielstand ein.");

	public SaveGameDialog(Window owner, FileSystem.GameName game) {
		super(owner, "Spiel Speichern", game);
		this.add(new PaddedPanel(instruction, 10, 10), BorderLayout.NORTH);
		
		buttonPan.add(butSave);
		buttonPan.add(butCancel);
		panSouth.setLayout(new GridLayout(2,1));
		panSouth.add(new PaddedPanel(textField, 10, 10));
		panSouth.add(buttonPan);
		this.add(panSouth, BorderLayout.SOUTH);
		
		saveList.addListSelectionListener(new ListSelectionListener() {
			@Override	public void valueChanged(ListSelectionEvent e) {
				itemSelected();
			}
		});
		
		butSave.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				clickedSave();
			}
		});
		
		butCancel.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
	}

	
	private void itemSelected(){
		int selectedIndex=saveList.getSelectedIndex();
		String selectedName=savedGameNames[selectedIndex];
		textField.setText(selectedName);
	}
	
	private void clickedSave(){
		String enteredName=textField.getText();
		if(isValidFilename(enteredName)){
			//test whether such a file already exists in the file system
			boolean fileExists=false;
			for(String existingName: savedGameNames){
				if(enteredName.equals(existingName)){
					fileExists=true;
					break;
				}
			}
			if(fileExists){
				boolean override=DecisionDialog.askQuestion(this, "Überschreiben",
						"Wollen sie den Spielstand \""+"asas"+"\" überschreiben?");
				if(!override)
					return;
			}
			returnFile=getSelectedFile();
			dispose();
		}
		else{
			//inform user about what went wrong...
			if(enteredName.equals(""))
				new MessageDialog(this, "Error", "Bitte geben sie einen Namen für das Siel ein.");
			else{
				String invalidChar=getInvalidChar(enteredName);
				if(invalidChar!=null)
					new MessageDialog(this, "Error", "Das Zeichen \""+invalidChar+"\" ist nicht erlaubt.");
			}
		}
	}
	public static File askForFile(Window owner, FileSystem.GameName game){
		System.out.println("Hello from askForFile(...)");
		SaveGameDialog sgf=new SaveGameDialog(owner, game);
		sgf.setVisible(true);
		return sgf.returnFile;
	}

}